let recognizing = false;
let recognition;
let isSpeaking = false;
const synth = window.speechSynthesis;

function toggleVoiceMode() {
    const toggleButton = document.getElementById('voice-mode-btn');
    recognizing = !recognizing;

    if (recognizing) {
        toggleButton.textContent = '语音模式（开）';
        toggleButton.classList.remove('disabled');
        if (!isSpeaking) {
            startRecognition();
        }
    } else {
        toggleButton.textContent = '语音模式（关）';
        toggleButton.classList.add('disabled');
        stopRecognition();
    }
}

function startRecognition() {
    if (!('webkitSpeechRecognition' in window)) {
        alert('您的浏览器不支持语音识别功能。');
        return;
    }

    if (!recognition) {
        recognition = new webkitSpeechRecognition();
        recognition.continuous = true;
        recognition.interimResults = false;
        recognition.lang = 'zh-CN';
    }

    recognition.onresult = (event) => {
        const transcript = event.results[event.results.length - 1][0].transcript.trim();
        document.getElementById('chat-input').value = transcript;
        processChat();
    };

    recognition.onerror = (event) => {
        console.error('语音识别错误:', event.error);
    };

    recognition.onend = () => {
        if (!isSpeaking && recognizing) {
            recognition.start();
        }
    };

    if (!isSpeaking) {
        recognition.start();
    }
}

function stopRecognition() {
    if (recognition) {
        recognition.stop();
    }
}

function speakMessage(message) {
    if (!recognizing) return;

    isSpeaking = true;
    stopRecognition();

    const utterance = new SpeechSynthesisUtterance(message);

    utterance.onend = () => {
        isSpeaking = false;
        if (recognizing) {
            startRecognition();
        }
    };

    synth.speak(utterance);
}
function addChatMessage(message, isUser = true) {
    const chatDisplay = document.getElementById('chat-display');
    const messageElement = document.createElement('div');
    messageElement.textContent = message;
    messageElement.classList.add('chat-message', isUser ? 'user' : 'ai');
    chatDisplay.appendChild(messageElement);
    chatDisplay.scrollTop = chatDisplay.scrollHeight;

    if (!isUser) {
        speakMessage(message);
    }
}

function handleChatInput(event) {
    if (event.key === 'Enter') {
        processChat();
    }
}

document.addEventListener('DOMContentLoaded', () => {
    fetch(`/static/chat_response.txt?timestamp=${Date.now()}`)
        .then(response => response.text())
        .then(data => {
            parseChatResponses(data);
        })
        .catch(error => {
            console.error('无法加载信息文件:', error);
        });

    const pageId = document.body.dataset.pageId;

    const welcomeMessages = {
        page1: `您好，欢迎来到页面1的小助手！请问有什么我可以帮助您的吗？\n`,
    };

    const welcomeMessage = welcomeMessages[pageId];
    if (welcomeMessage) {
        addChatMessage(welcomeMessage, false);
    } else {
        console.warn(`未知页面ID: ${pageId}，您好！`);
    }
});

const chatResponses = {};

function parseChatResponses(data) {
    const lines = data.split('\n');
    let currentKeyword = null;
    let currentResponse = [];

    lines.forEach(line => {
        line = line.trim();
        if (line === '') {
            if (currentKeyword && currentResponse.length > 0) {
                chatResponses[currentKeyword.trim()] = currentResponse.join(' ');
            }
            currentKeyword = null;
            currentResponse = [];
        } else if (!currentKeyword) {
            currentKeyword = line;
        } else {
            currentResponse.push(line);
        }
    });

    if (currentKeyword && currentResponse.length > 0) {
        chatResponses[currentKeyword.trim()] = currentResponse.join(' ');
    }
}

function processChat() {
    const input = document.getElementById('chat-input');
    const userMessage = input.value.trim();
    if (!userMessage) return;
    addChatMessage(userMessage, true);
    input.value = '';

    const matchedKeyword = Object.keys(chatResponses).find(keyword => userMessage.includes(keyword));

    if (matchedKeyword) {
        addChatMessage(chatResponses[matchedKeyword], false);
        return;
    }

    const commonKeywordActions = {
        '十分感谢': () => addChatMessage('不客气，很高兴为您服务。', false),
    };

    const page1KeywordActions = {
        '上传图片': () => {
            addChatMessage('开始执行指令：从电脑中选择图片上传', false);
            document.querySelector('label[for="image"]').click();
        },
        '选择图片': () => {
            addChatMessage('开始执行指令：从电脑中选择图片', false);
            document.querySelector('label[for="image"]').click();
        },
        '识别图片': () => {
            addChatMessage('开始执行指令：识别图片作者', false);
            document.querySelector('button[type="submit"]').click();
        },
    };

    const page2KeywordActions = {
        '返回': () => {
            addChatMessage('开始执行指令：返回上传页面', false);
            document.querySelector('.back-button').click();
        },
    };

    const pageSpecificActions = (() => {
        const pageIdentifier = document.body.dataset.pageId;
        if (pageIdentifier === 'page1') {
            return page1KeywordActions;
        } else if (pageIdentifier === 'page2') {
            return page2KeywordActions;
        }
        return {};
    })();

    const keywordActions = { ...commonKeywordActions, ...pageSpecificActions };

    if (userMessage in keywordActions) {
        keywordActions[userMessage]();
    } else {
        addChatMessage(`未找到相关信息，请检查输入是否正确: "${userMessage}"`, false);
    }
}